//
//  ScrollViewController.m
//  Style
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#define ViewWidth(v)                        v.frame.size.width
#define ViewHeight(v)                       v.frame.size.height
#define ScreenWidth          [[UIScreen mainScreen] bounds].size.width
#define ScreenHeight         [[UIScreen mainScreen] bounds].size.height
#import "YLHeadScrollViewController.h"
#import "ArticleTableView_model.h"
#import "AFNetWorkingW.h"
#import "YLDetail_model.h"
#import "UMSocial.h"
#import "CoreDataManager.h"
#import "Collect.h"
#import "YLSearchModel.h"
@interface YLHeadScrollViewController () <UIWebViewDelegate>
@property (nonatomic, retain) CoreDataManager *manager;
@property (nonatomic, retain) NSMutableDictionary *mDic;
@property (nonatomic, retain) NSString *html;
@property (nonatomic, assign) NSInteger i;
@property (nonatomic, retain) UIWebView *webView;
@property (nonatomic, assign) float size;
@property (nonatomic, retain) NSString *urlStr;
@property (nonatomic, retain) NSString *url;
@property (nonatomic, retain) UIView *viewSize;
@property (nonatomic, retain) UIButton *buttonCollect;
@property (nonatomic, strong) UIActivityIndicatorView *activity;
@end

@implementation YLHeadScrollViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.tabBarController.tabBar.hidden = YES;
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (self.searchModel.contentid != nil) {
        self.detail_model = [[YLDetail_model alloc] init];
        self.detail_model.typeId = self.searchModel.contentid;
        self.detail_model.content = self.searchModel.shortcontent;
        self.detail_model.title = self.searchModel.title;
        self.detail_model.coverimg = self.searchModel.icon;
    }
    
    self.size = 17;
    self.view.backgroundColor = [UIColor whiteColor];
    //CGRectMake(ViewWidth(self.view) / 3, ViewHeight(self.view) - 44, ViewWidth(self.view) * 2 / 3, 44)
    self.manager = [CoreDataManager defaults];
    UIView *viewM = [[UIView alloc] initWithFrame:CGRectMake(ViewWidth(self.view) / 3, ViewHeight(self.view) - 108, ViewWidth(self.view) / 3, 44)];
    viewM.backgroundColor = [UIColor whiteColor];
    viewM.layer.borderWidth = 0.3;
    [self.view addSubview:viewM];
    
    UIView *viewR = [[UIView alloc] initWithFrame:CGRectMake(ViewWidth(self.view) * 2 / 3, ViewHeight(self.view) - 108, ViewWidth(self.view) / 3, 44)];
    viewR.backgroundColor = [UIColor whiteColor];
    viewR.layer.borderWidth = 0.3;
    [self.view addSubview:viewR];
    
    self.viewSize = [[UIView alloc] initWithFrame:CGRectMake(ViewWidth(self.view) / 3, ViewHeight(self.view) - 108, ViewWidth(self.view) * 2 / 3, 44)];
    self.viewSize.backgroundColor = [UIColor whiteColor];
    self.viewSize.layer.borderWidth = 0.3;
    self.viewSize.alpha = 0;
    [self.view addSubview:self.viewSize];
    
    UIButton *buttonS = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonS.frame = CGRectMake(0, 0, ViewWidth(self.viewSize) / 3, ViewHeight(self.viewSize));
    [buttonS setImage:[UIImage imageNamed:@"S"] forState:UIControlStateNormal];
    [self.viewSize addSubview:buttonS];
    [buttonS addTarget:self action:@selector(changeS) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *buttonM = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonM.frame = CGRectMake(ViewWidth(self.viewSize) / 3, 0, ViewWidth(self.viewSize) / 3, ViewHeight(self.viewSize));
    [buttonM setImage:[UIImage imageNamed:@"M"] forState:UIControlStateNormal];
    [self.viewSize addSubview:buttonM];
    [buttonM addTarget:self action:@selector(changeM) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *buttonB = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonB.frame = CGRectMake(ViewWidth(self.viewSize) / 3 * 2, 0, ViewWidth(self.viewSize) / 3, ViewHeight(self.viewSize));
    [buttonB setImage:[UIImage imageNamed:@"B"] forState:UIControlStateNormal];
    [self.viewSize addSubview:buttonB];
    [buttonB addTarget:self action:@selector(changeB) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *viewL = [[UIView alloc] initWithFrame:CGRectMake(0, ViewHeight(self.view) - 108, ViewWidth(self.view) / 3, 44)];
    viewL.backgroundColor = [UIColor whiteColor];
    viewL.layer.borderWidth = 0.3;
    [self.view addSubview:viewL];
    
    /* 大小按钮 */
    UIButton *buttonSize = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonSize.frame = CGRectMake(ViewWidth(viewL) / 2 - 15, ViewHeight(viewL) / 2 - 15, 30, 30);
    [buttonSize setImage:[UIImage imageNamed:@"size"] forState:UIControlStateNormal];
    [buttonSize addTarget:self action:@selector(buttonSizeClicked:) forControlEvents:UIControlEventTouchUpInside];
    [viewL addSubview:buttonSize];
    
    if (self.detail_model.typeId != nil) {
        /* 收藏按钮 */
        self.buttonCollect = [UIButton buttonWithType:UIButtonTypeCustom];
        self.buttonCollect.frame = CGRectMake(ViewWidth(viewM) / 2 - 15, ViewHeight(viewM) / 2 - 15, 30, 30);
        NSInteger conut = [self.manager search:self.detail_model];
        if (conut == 0) {
            [self.buttonCollect setImage:[UIImage imageNamed:@"collectE"] forState:UIControlStateNormal];
        }else{
            [self.buttonCollect setImage:[UIImage imageNamed:@"collectA"] forState:UIControlStateNormal];
        }
        [viewM addSubview:self.buttonCollect];
        [self.buttonCollect addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
        if (self.detail_model.title.length > 10) {
            NSString *str = [self.detail_model.title substringToIndex:10];
            self.title = [NSString stringWithFormat:@"%@", str];
        }else{
            self.title = self.detail_model.title;
        }
    }else{
        viewR.frame = CGRectMake(ViewWidth(self.view) / 3, ViewHeight(self.view) - 108, ViewWidth(self.view) * 2 / 3, 44);
        self.title = @"推荐";
    }
    
    /* 分享按钮 */
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonShare.frame = CGRectMake(ViewWidth(viewR) / 2 - 15, ViewHeight(viewR) / 2 - 15, 30, 30);
    [buttonShare setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [viewR addSubview:buttonShare];
    [buttonShare addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64 - 44)];
    [self.view addSubview:self.webView];
    
    self.activity = [[UIActivityIndicatorView alloc] init];
    self.activity.color = [UIColor blackColor];
    self.activity.frame = CGRectMake(0, 0, 50, 50);
    self.activity.center = self.view.center;
    [self.view addSubview:self.activity];
    [self.activity startAnimating];
    
    [self dataHandle];
    
}

- (void)dataHandle
{
    self.i = 0;
    if (self.detail_model.typeId != nil) {
        self.url = self.detail_model.typeId;
        self.urlStr = self.detail_model.typeId;
    }else{
        self.url = self.articleTable_model.url;
        NSArray *arr = [self.url componentsSeparatedByString:@"/"];
        self.urlStr = [arr lastObject];
    }
    [AFNetWorkingW netWorkWithURL:@"http://api2.pianke.me/article/info" body:[NSString stringWithFormat:@"auth=&client=1&contentid=%@&deviceid=BA920378-52B5-43F2-BE1A-5404120EDD7A&version=3.0.6", self.urlStr] resultBlock:^(id result) {
        self.mDic = result;
        NSDictionary *dic = [self.mDic objectForKey:@"data"];
        self.html = [dic objectForKey:@"html"];
        
        [self.webView loadHTMLString:self.html baseURL:nil];
        self.webView.delegate = self;
        self.webView.scrollView.bounces = NO;
        
       
        
    }];
}


/* webView自适应 */
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //字体颜色
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'"];
    //页面背景色
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].style.background='#2E2E2E'"];
    
    //图片自适应
    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth= 305;"//缩放系数,调动这个参数可以改变图片的宽度
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "oldwidth = myimg.width;"
     "if (oldwidth >= 300) {"
     "myimg.width = maxwidth;"
     "myimg.height = myimg.height;"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    self.size = 200;
    
    self.i++;
    [self hideWaiting];
    [self.activity stopAnimating];

}

/* 改变字体大小按钮 */
- (void)buttonSizeClicked:(UIButton *)button
{
    [UIView animateWithDuration:0.3 animations:^{
        self.viewSize.alpha = 1;
    }];
}

- (void)changeS
{
    //     改变字体大小
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'";
    [self.webView stringByEvaluatingJavaScriptFromString:str];
    [UIView animateWithDuration:0.3 animations:^{
        self.viewSize.alpha = 0;
    }];
}

- (void)changeM
{
    //     改变字体大小
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '125%'";
    [self.webView stringByEvaluatingJavaScriptFromString:str];
    [UIView animateWithDuration:0.3 animations:^{
        self.viewSize.alpha = 0;
    }];
}

- (void)changeB
{
    //     改变字体大小
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '150%'";
    [self.webView stringByEvaluatingJavaScriptFromString:str];
    [UIView animateWithDuration:0.3 animations:^{
        self.viewSize.alpha = 0;
    }];
}

/* 收藏 */
- (void)collect:(UIButton *)button
{
    [self.manager collect:self.detail_model];
    NSInteger conut = [self.manager search:self.detail_model];
    if (conut != 0) {
        [button setImage:[UIImage imageNamed:@"collectA"] forState:UIControlStateNormal];
    }else{
        [button setImage:[UIImage imageNamed:@"collectE"] forState:UIControlStateNormal];
    }
    [self.manager saveContext];
}

/* 分享 */
- (void)share
{
    //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55e26fd6e0f55a666100490e"
                                      shareText:self.detail_model.coverimg
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession, UMShareToEmail,nil]
                                       delegate:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (self.i <= 0) {
        return YES;
    }else
        return NO;
}

//消除滚动轮指示器
- (void)hideWaiting
{
    [[self.view viewWithTag:9998] removeFromSuperview];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end

